package com.orangelife.mobile.washcar.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.util.OrangePhoneUtil;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHandler;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.MoneyUtil;
import com.curry.orangelife.mobile.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsOrder.biz.OrderBiz;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.interfaze.IOuttradenoCallBack;
import com.orangelife.mobile.pay.biz.PayManageImpl;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.washcar.adapter.WashCarDetailListAdapter;
import com.orangelife.mobile.washcar.biz.WashCarBiz;
import com.orangelife.mobile.washcar.entity.WashCarDetailEntity;
import com.orangelife.mobile.widget.ScrollListView;
import com.thirdsdk.qiniu.QiniuHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 上门洗车订单详情
 * Created by ${shz} on 2016/1/18.
 */
public class WashCarDetailActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tvRight)
    TextView tvRight;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.tv_username)
    TextView tvUsername;
    @Bind(R.id.tv_userphone)
    TextView tvUserphone;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.ivGoods)
    ImageView ivGoods;
    @Bind(R.id.tvGoodsName)
    TextView tvGoodsName;
    @Bind(R.id.tvUnitPrice)
    TextView tvUnitPrice;
    @Bind(R.id.tvMarkerPrice)
    TextView tvMarkerPrice;
    @Bind(R.id.btnCancel)
    Button btnCancel;
    @Bind(R.id.btnPay)
    Button btnPay;
    @Bind(R.id.llBtn)
    LinearLayout llBtn;
    @Bind(R.id.btnPayAgain)
    Button btnPayAgain;
    @Bind(R.id.slGoodsRentStates)
    ScrollListView slGoodsRentStates;
    @Bind(R.id.tvOrderNumber)
    TextView tvOrderNumber;
    @Bind(R.id.tvOrderStatus)
    TextView tvOrderStatus;
    @Bind(R.id.tvOrderHaveTime)
    TextView tvOrderHaveTime;
    @Bind(R.id.tvPlaceOrderTime)
    TextView tvPlaceOrderTime;
    @Bind(R.id.tvPoints)
    TextView tvPoints;
    @Bind(R.id.tvOrderMoney)
    TextView tvOrderMoney;
    @Bind(R.id.llOrderHaveTime)
    LinearLayout llOrderHaveTime;
    private String orderID;
    private WashCarDetailListAdapter statesAdapter;
    //订单跟踪
    private List<Map<String, Object>> washCarDetailFollowEntities;
    //订单状态
    private String orderStatues;
    //d洗车订单详情
    private WashCarDetailEntity washCarDetailEntity;
    private Dialog mDialog;
    private String points;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wash_car_detail);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        orderID = String.valueOf(intent.getExtras().get("orderID"));
        initView();
        getWashCarDetail();
        setListener();
    }


    /**
     * 初始化界面的信息
     */
    private void initView() {
        tvTitle.setText("订单详情");
        ivTitleRight.setVisibility(View.VISIBLE);
        ivTitleRight.setBackgroundResource(R.drawable.ic_house_phone);
    }

    /**
     * 请求dd洗车订单详情
     */
    private void getWashCarDetail() {
        HashMap<String, String> map = new HashMap<>();
        map.put("{orderID}", orderID);
        dialog = DialogHelper.getInstance().createLoadingDialog(WashCarDetailActivity.this);
        dialog.show();
        WashCarBiz.getInstance().getWashCarDetail(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                DialogHelper.closeDialog(dialog);
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    washCarDetailEntity = WashCarBiz.handleWashCarDetail(response, errCode);
                    HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                            .jsonToMap(String.valueOf(response));
                    washCarDetailFollowEntities = (List<Map<String, Object>>) map.get("pageEntity");
                    setContent(washCarDetailEntity);
                    if (washCarDetailFollowEntities.size() != 0) {
                        if (washCarDetailFollowEntities.size() == 1) {
                            btnPay.setVisibility(View.GONE);
                            if (orderStatues.equals("4")) {
                                llBtn.setVisibility(View.GONE);
                                btnPayAgain.setVisibility(View.VISIBLE);
                            }
                        } else {
                            llBtn.setVisibility(View.GONE);
                            btnPayAgain.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置界面上的信息
     *
     * @param washCarDetailEntity
     */
    private void setContent(WashCarDetailEntity washCarDetailEntity) {
        tvUsername.setText(String.valueOf(washCarDetailEntity.getShipName()));
        tvUserphone.setText(String.valueOf(washCarDetailEntity.getShipPhone()));
        tvAddress.setText(String.valueOf(washCarDetailEntity.getShipAddr()));
        tvOrderNumber.setText(String.valueOf(washCarDetailEntity.getOrderID()));
        orderStatues = String.valueOf(washCarDetailEntity.getOrderStatus());
        points = String.valueOf(washCarDetailEntity.getPoints());
        JudeOrderStatues1(orderStatues);
        if (!(orderStatues.equals("0") || orderStatues.equals("2"))) {
            llOrderHaveTime.setVisibility(View.GONE);
        }
        if (orderStatues.equals("2")) {
            tvOrderHaveTime.setText("订单已超时不能支付");
            btnPay.setVisibility(View.GONE);
            llBtn.setVisibility(View.GONE);
            btnPayAgain.setVisibility(View.VISIBLE);
        } else {
            startTimer(String.valueOf(washCarDetailEntity.getTime()));
            statesAdapter = new WashCarDetailListAdapter(WashCarDetailActivity.this, washCarDetailFollowEntities);
            slGoodsRentStates.setAdapter(statesAdapter);
        }
        tvPlaceOrderTime.setText(DateUtil.getInstance().tranStringForDate(String.valueOf(washCarDetailEntity.getOrderTime())));
        tvOrderMoney.setText(Constant.RMB_FLAG + MoneyUtil.handleMoney(String.valueOf(washCarDetailEntity.getTotalCost())));
        List<Map<String, Object>> snap = washCarDetailEntity.getSnap();
        tvGoodsName.setText(String.valueOf(snap.get(0).get("goodsName")));
        ImageLoader.getInstance().displayImage(QiniuHelper.getUrlWithQiniuImageSize(String.valueOf(snap.get(0).get("goodsLogo")), QiniuHelper.QiniuImageSize.IMAGE_SIZE_EXTRA_SMALL_PNG), ivGoods);
        String goodsCost = String.valueOf(washCarDetailEntity.getGoodsCost());
        String totalCost = String.valueOf(washCarDetailEntity.getTotalCost());
        tvUnitPrice.setText(Constant.RMB_FLAG + MoneyUtil.handleMoney(goodsCost));
        tvMarkerPrice.setText(Constant.RMB_FLAG + goodsCost);
        OrderBiz.setTextInfo(tvPoints, getString(R.string.format_zeng_points), points);
//        if (goodsCost.equals(totalCost)) {
//            tvMarkerPrice.setText("");
//        } else {
//            tvMarkerPrice.setText("￥" + goodsCost);
        //文字划掉显示
        tvMarkerPrice.getPaint().setFlags(
                Paint.STRIKE_THRU_TEXT_FLAG);
//        }
    }

    /**
     * 剩余时间
     *
     * @param second
     */
    private void startTimer(String second) {
        CountDownHandler handler = new CountDownHandler(tvOrderHaveTime, 0);
        handler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
            @Override
            public void onFinish() {
                if (orderStatues.equals("0")) {
                    tvOrderHaveTime.setText("订单已超时不能支付");
                    tvOrderStatus.setText("已超时");
                    btnPay.setVisibility(View.GONE);
                    llBtn.setVisibility(View.GONE);
                    btnPayAgain.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onCountDown(String currentSecond) {

            }
        });
        handler.startTimer(second);
    }

    /**
     * 取消dd洗车的订单
     */
    private void CancleWashCarOrder() {

        WashCarBiz.getInstance().putCancleWashCarOrder(orderID, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    DialogHelper.closeDialog(mDialog);
                    ToastHelper.getInstance()._toast("取消订单成功!");
                    finish();
                }
            }
        });
    }

    /**
     * 账单的状态判断,并设值
     * 订单转态 0待付款，1已付款，2已超时，3已派单，4已取消，5服务中，6已完成，8已退款
     */
    private void JudeOrderStatues1(String orderStatues) {
        switch (orderStatues) {
            case "0":
                tvOrderStatus.setText("待付款");
                break;
            case "1":
                tvOrderStatus.setText("已付款");
                break;
            case "2":
                tvOrderStatus.setText("已超时");
                break;
            case "3":
                tvOrderStatus.setText("已派单");
                break;
            case "4":
                tvOrderStatus.setText("已取消");
                break;
            case "5":
                tvOrderStatus.setText("服务中");
                break;
            case "6":
                tvOrderStatus.setText("已完成");
                break;
            case "8":
                tvOrderStatus.setText("已退款");
                break;
        }
    }


    /**
     * 账单跟踪状态判断,并设值
     * 订单转态 0待付款，1已付款，2已超时，3已派单，4已取消，5服务中，6已完成，8已退款
     */
    private void JudeOrderStatues(String orderStatues) {
        switch (orderStatues) {
            case "0":
                tvOrderStatus.setText("待付款");
                break;
            case "1":
                tvOrderStatus.setText("支付成功");
                break;
            case "2":
                tvOrderStatus.setText("已超时");
                break;
            case "3":
                tvOrderStatus.setText("派单成功");
                break;
            case "4":
                tvOrderStatus.setText("订单取消");
                break;
            case "5":
                tvOrderStatus.setText("开始服务");
                break;
            case "6":
                tvOrderStatus.setText("服务完成");
                break;
            case "8":
                tvOrderStatus.setText("已退款");
                break;
        }
    }

    private void setListener() {
        ivTitleRight.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);
        btnPay.setOnClickListener(listener);
        btnPayAgain.setOnClickListener(listener);
    }

    /**
     * 点击监听
     */
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.iv_title_right:
                    OrangePhoneUtil.callCustomerService2(WashCarDetailActivity.this);
                    break;
                case R.id.btnCancel:
                    final ConfirmDialog dialog = new ConfirmDialog(WashCarDetailActivity.this, "温馨提示", "是否取消订单？", "取消", "确定");
                    dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                        @Override
                        public void doLeft() {
                            dialog.dismiss();

                        }

                        @Override
                        public void doRight() {
                            mDialog = DialogHelper.getInstance().createLoadingDialog(WashCarDetailActivity.this);
                            mDialog.show();
                            CancleWashCarOrder();
                        }
                    });
                    dialog.show();
                    break;
                case R.id.btnPayAgain:
                    IntentHelper.getInstances().getIntent(WashCarDetailActivity.this, WashCarActivity.class);
                    finish();
                    break;
                case R.id.btnPay:
                    mDialog = DialogHelper.getInstance().createLoadingDialog(WashCarDetailActivity.this);
                    mDialog.show();
                    payment();
                    break;
            }
        }
    };

    /**
     * 设置付款跳转
     */
    private void payment() {
        final PayManageImpl payManageImpl = new PayManageImpl(new IOuttradenoCallBack() {
            @Override
            public void data(JSONObject jsonObject) {
                ExitApplication.getInstance().addMainActivity(WashCarDetailActivity.this);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                try {
                    Map<String, Object> entity = JSONHelper.jsonToMap(jsonObject.get("entity").toString());
                    bundle.putString("outtradeno", entity.get("outtradeno").toString());
                    bundle.putString("points", entity.get("points").toString());
                    bundle.putString("orderType", String.valueOf(entity.get("orderType")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                bundle.putString("orderInfo", "DD洗车");
                bundle.putString("totalPrice", Constant.RMB_FLAG + washCarDetailEntity.getTotalCost());
                bundle.putString("totalCost", washCarDetailEntity.getTotalCost());
                bundle.putString("orderID", orderID);
                bundle.putString("status", "goods");
                bundle.putBoolean("orderList", true);/**支付成功后返回商品列表*/
                bundle.putString(PaymentModule.PAID_METHOD, PaymentModule.mode[11]);
                intent.putExtras(bundle);
                intent.setClass(WashCarDetailActivity.this, UsersPaidActivity.class);
                DialogHelper.closeDialog(mDialog);
                startActivity(intent);
            }
        });
        payManageImpl.getOuttradenoFromServer(orderID, 16);
    }
}
